var path = require('path');
var webpack = require('webpack');

var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');

var rootPath = path.resolve(__dirname, '..');
var fontFilePath = 'assets/icons/[name].[ext]';
var imgFilePath = 'assets/imgs/[name].[ext]';
var codeRootPath = path.join(rootPath, 'app');

var hotMiddlewareScript = 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true';

module.exports = (env) => {

  const COMMON_CONFIG = {

    entry: {
      vendor: path.resolve(codeRootPath, 'vendor.js'),
      main: path.resolve(codeRootPath, 'index.js')
    },

    output: {
      path: path.join(rootPath, 'dist'),
      filename: path.join('scripts', `[name]_${env.timestamp}.js`),
      chunkFilename: path.join('scripts', `[name]_${env.timestamp}.js`)
    },

    module: {
      rules: [{
        enforce: 'pre',
        test: /\.(js|vue)$/,
        use: "eslint-loader",
        exclude: /node_modules/
      }, {
        test: /\.js$/,
        use: 'babel-loader'
      }, {
        test: /\.vue$/,
        use: 'vue-loader'
      }, {
        test: /\.html$/,
        use: 'html-loader'
      }, {
        test: /\.(woff|woff2|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
        use: {
          loader: 'file-loader',
          options: {
            name: fontFilePath
          }
        }
      }, {
        test: /\.(png)(\?v=\d+\.\d+\.\d+)?$/,
        use: {
          loader: 'file-loader',
          options: {
            name: imgFilePath
          }
        }
      }]
    },

    plugins: [
      new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor',
        chunks: ['vendor', 'main']
      }),
      new webpack.optimize.CommonsChunkPlugin({
        name: 'main',
        chunks: ['main']
      }),
      new webpack.DefinePlugin({
        'process.env': {
          'NODE_ENV': JSON.stringify('production')
        }
      }),
      new ExtractTextPlugin(`style_${env.timestamp}.css`),
      new HtmlWebpackPlugin({
        template: 'resources/index.html',
        chunks: ['vendor', 'main']
      })
    ],

    resolve: {
      extensions: ['.js', '.vue', '.json', '.png', '.html'],
      alias: {
        app: path.resolve(rootPath, 'app'),
        cmpts: path.resolve(rootPath, 'app/components'),
        mdls: path.resolve(rootPath, 'app/modules'),
        store: path.resolve(rootPath, 'app/store'),
        api: path.resolve(rootPath, 'app/api'),
        actionTypes: path.resolve(rootPath, 'app/constants/action-types'),
        mutationTypes: path.resolve(rootPath, 'app/constants/mutation-types'),
        constants: path.resolve(rootPath, 'app/constants'),
        vue: 'vue/dist/vue.js'
      }
    }

  };

  const ENV_CONFIG = {

    DEBUG: {
      devtool: 'source-map',

      module: {
        rules: COMMON_CONFIG.module.rules.concat([
          {
            test: /\.css$/,
            use: ExtractTextPlugin.extract({
              use: [ 'style-loader', 'css-loader']
            })
          }
        ])
      }
    },

    PRD: {
      module: {
        rules: COMMON_CONFIG.module.rules.concat([
          {
            test: /\.css$/,
            use: ExtractTextPlugin.extract({
              use: ['style-loader', {
                loader: "css-loader",
                options: {
                  minimize: true
                }
              }]
            })
          }
        ])
      },

      plugins: COMMON_CONFIG.plugins.concat([
        new webpack.optimize.UglifyJsPlugin({
          compress: {
            warnings: false,
          },
          output: {
            comments: false,
          },
        })
      ]),
      resolve: {...COMMON_CONFIG.resolve, alias: {
        ...COMMON_CONFIG.resolve.alias, vue: 'vue/dist/vue.min.js'
      }}
    },

    DEV: {
      devtool: 'source-map',

      entry: {
        client: ['webpack-hot-middleware/client.js', hotMiddlewareScript],
        vendor: [path.resolve(codeRootPath, 'vendor.js'), hotMiddlewareScript],
        main: [path.resolve(codeRootPath, 'index.js'), hotMiddlewareScript]
      },

      output: {
        path: path.join(__dirname, 'dev'),
        publicPath: '/',
        filename: path.join('scripts', `[name].js`),
        chunkFilename: path.join('scripts', `[name].js`)
      },

      module: {
        rules: COMMON_CONFIG.module.rules.concat([
          {
            test: /\.css$/,
            use: [ "style-loader", "css-loader" ]
          }
        ])
      },

      plugins: [
        new webpack.optimize.OccurrenceOrderPlugin(),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoEmitOnErrorsPlugin()
      ]
    }

  };

  return Object.assign(COMMON_CONFIG, ENV_CONFIG[env.BUILD_ENV]);

};
